﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoKnow.CloudEdu.CMS.Host.Models;
using DoKnow.CloudEdu.Common.Attrs;
using DoKnow.CloudEdu.Common.Consts;
using DoKnow.CloudEdu.DataContract.Model.Base;
using DoKnow.Common.Utility;
using Newtonsoft.Json;
using Webdiyer.WebControls.Mvc;

namespace DoKnow.CloudEdu.CMS.Host.Controllers
{
    public class AuthorityController : BaseController
    {
        //
        // GET: /Authority/

        public ActionResult Index(BSRolePageInfo request)
        {
            return QueryBsRole(request);
        }
        public ActionResult QueryBsRole(BSRolePageInfo request)
        {
            RoleDatas roles = HttpHelper.Post<RoleDatas>(Server + ServicePath.RoleRead,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "RetrieveRoles",
                    Pars =
                      new
                      {
                          role = EmitHelper.Map<BSRolePageInfo, BSRoleInfo>(request),
                          page = EmitHelper.Map<BSRolePageInfo, PageInfo>(request)
                      }
                }));
            if (null != roles && null != roles.RoleEntitys && roles.RoleEntitys.Count > 0)
            {
                var model = new PagedList<BSRolePageInfo>(EmitHelper.Map<BSRoleInfo, BSRolePageInfo>(roles.RoleEntitys), request.PageIndex, request.PageSize, roles.Total);
                return View("Index", model);
            }
            return View("Index"); 
        }
        [MenuItem("~/Authority/Index")]
        public ActionResult EditModules(int roleId, string roleName)
        {
            ViewBag.RoleId = roleId;
            ViewBag.RoleName = roleName;
            return View();
        }
        [HttpPost]
        public ActionResult UpdateRoleModuleRelationship()
        {
            int roleId = int.Parse(Request["roleId"]);
            List<int> moduleIds = new List<int>();
            List<BSRoleModuleInfo> list = new List<BSRoleModuleInfo>();
            if (!string.IsNullOrEmpty(Request["moduleIds"]))
            {
                moduleIds = Request["moduleIds"].Split(',').Select(n => int.Parse(n)).ToList();
                moduleIds.ForEach(n => list.Add(new BSRoleModuleInfo() { RoleID = roleId, ModuleID = n }));
            }

            RoleModuleDatas model = new RoleModuleDatas();
            model.RoleModules = list;
            model.RoleID = roleId;

            var response = HttpHelper.Post(Server + ServicePath.RoleWrite,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "CreateBSRoleModules",
                    Pars =
                      new
                      {
                          roleModules = model
                      }
                }));
            if (response.IsSuccess)
            {
                CacheHelper.Remove<List<BSRoleModuleInfo>>(CacheKey.BSRoleModuleFull);
            }
            //更新RoleModule的缓存信息
            return RedirectToAction("Index", new { gridStage = Request.QueryString["gridStage"] });
        }

        public ActionResult GetAllModulesWithRole(int id)
        {
            List<JsTreeNode> result = CurCache.BSModuleFull.OrderBy(o => o.ParentID).ThenBy(o => o.ModuleOrder).Select(
               n => new JsTreeNode
               {
                   icon = n.ModuleIcon,
                   id = n.ID.ToString(),
                   parent = (n.ParentID == null || n.ParentID == 0) ? "#" : n.ParentID.ToString(),
                   text = n.ModuleName,
                   state = new State
                   {
                       opened = true,
                       disabled = false,
                       selected = false
                   }
               }
               ).ToList();

            var list = HttpHelper.Post<RoleModuleDatas>(Server + ServicePath.RoleRead,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "RetrieveBSRoleModulesByRoleID",
                    Pars =
                      new
                      {
                          roleID = id
                      }
                }));
            if (null != list.RoleModules)
            {
                foreach (var item in list.RoleModules)
                {
                    foreach (var node in result)
                    {
                        if (item.ModuleID == int.Parse(node.id))
                        {
                            node.state.selected = true;
                            break;
                        }
                    }
                }
            }
            return Json(result);
        }

        [MenuItem("~/Authority/Index")]
        public ActionResult AddUserRoleRelationShip()
        {
            var Ids = Request["selectedUsers"];
            int roleId = int.Parse(Request["roleId"]);
            if (!string.IsNullOrEmpty(Ids))
            {
                List<string> selectedUserIds = Ids.Split(',').ToList();
                List<BSUserRoleInfo> list = new List<BSUserRoleInfo>();
                selectedUserIds.ForEach(n => list.Add(new BSUserRoleInfo() { RoleID = roleId, UserID = int.Parse(n) }));
                UserRoleDatas model = new UserRoleDatas();
                model.UserRoles = list;
                model.RoleID = roleId;

                var response = HttpHelper.Post(Server + ServicePath.UserWrite,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "CreateBSUserRoles",
                        Pars =
                          new
                          {
                              UserRoles = model
                          }
                    }));
                if (response.IsSuccess)
                {
                    //    AddOperationLog(
                    //BaseSystem.Model.BusinessTarget.Authority,
                    //BaseSystem.Model.BusinessAction.Edit,
                    //roleId,
                    //string.Format("用户[{0}]编辑角色{1}的用户权限", UserSession.Current.UserCode, result.DataContext.ROLE_CODE));
                }
            }
            ViewBag.RoleId = roleId;
            ViewBag.RoleName = Request["roleName"];
            return RedirectToAction("EditUsers", new { RoleId = roleId, RoleName = ViewBag.RoleName });
        }


        [MenuItem("~/Authority/Index")]
        public ActionResult RemoveUsersUnderRole()
        {
            var Ids = Request["selectedUsers"];
            int roleId = int.Parse(Request["roleId"]);
            if (!string.IsNullOrEmpty(Ids))
            {
                List<string> selectedUserIds = Ids.Split(',').ToList();
                List<int> models = new List<int>();
                selectedUserIds.ForEach(n => models.Add(int.Parse(n)));
                UserRoleDatas model = new UserRoleDatas();
                model.Users = models;
                model.RoleID = roleId;
                var response = HttpHelper.Post(Server + ServicePath.UserWrite,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "DeleteBSUserRoles",
                        Pars =
                          new
                          {
                              UserRoles = model
                          }
                    }));
                if (response.IsSuccess)
                {
                    //    AddOperationLog(
                    //BaseSystem.Model.BusinessTarget.Authority,
                    //BaseSystem.Model.BusinessAction.Edit,
                    //roleId,
                    //string.Format("用户[{0}]编辑角色{1}的用户权限", UserSession.Current.UserCode, result.DataContext.ROLE_CODE));
                }
            }
            ViewBag.RoleId = roleId;
            ViewBag.RoleName = Request["roleName"];
            return RedirectToAction("EditUsers", new { RoleId = roleId, RoleName = ViewBag.RoleName });
        }

        [MenuItem("~/Authority/Index")]
        public ActionResult EditUsers(int roleID, string roleName, BSUserPageInfo model)
        {

            ViewBag.RoleId = roleID;
            return QueryBsUser(new BSUserPageInfo() { PageIndex = (null != model) ? model.PageIndex : 1, RoleID = roleID },roleName);
        }
        public ActionResult QueryBsUser(BSUserPageInfo request,string roleName="")
        {
            //request.PageSize = PageSize;
            request.NotUnder = false;
            ViewBag.RoleName = roleName;
            UserDatas users = HttpHelper.Post<UserDatas>(Server + ServicePath.UserRead,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "RetrieveUsersByRole",
                        Pars =
                          new
                          {
                              user = EmitHelper.Map<BSUserPageInfo, BSUserInfo>(request),
                              roleid = request.RoleID,
                              notUnder = request.NotUnder,
                              page = EmitHelper.Map<BSUserPageInfo, PageInfo>(request)
                          }
                    }));
            if (null != users && null != users.UserEntitys && users.UserEntitys.Count > 0)
            {
                var model = new PagedList<BSUserPageInfo>(EmitHelper.Map<BSUserInfo, BSUserPageInfo>(users.UserEntitys), request.PageIndex, request.PageSize, users.Total);
                return View("EditUsers", model);
            }
            return View("EditUsers"); ;
        }

        [MenuItem("~/Authority/Index")]
        public ActionResult AddUsers(int roleID, string roleName, BSUserPageInfo model)
        {
            ViewBag.RoleId = roleID;
            ViewBag.RoleName = roleName;
            return GetUersNotUnderRoleId(new BSUserPageInfo() { PageIndex = (null != model) ? model.PageIndex : 1, RoleID = roleID, Code = Request["code"], RealName = Request["name"] });
        }

        public ActionResult GetUersNotUnderRoleId(BSUserPageInfo request)
        {
            //request.PageSize = PageSize;
            request.NotUnder = true;
            UserDatas users = HttpHelper.Post<UserDatas>(Server + ServicePath.UserRead,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "RetrieveUsersByRole",
                        Pars =
                          new
                          {
                              user = EmitHelper.Map<BSUserPageInfo, BSUserInfo>(request),
                              roleid = request.RoleID,
                              notUnder = request.NotUnder,
                              page = EmitHelper.Map<BSUserPageInfo, PageInfo>(request)
                          }
                    }));
            if (null != users && null != users.UserEntitys && users.UserEntitys.Count > 0)
            {
                var model = new PagedList<BSUserPageInfo>(EmitHelper.Map<BSUserInfo, BSUserPageInfo>(users.UserEntitys), request.PageIndex, request.PageSize, users.Total);
                return View("AddUsers", model);
            }
            return View("AddUsers"); ;
        }
    }
}
